<?php
/**
 * Created by PhpStorm.
 * User: xianxuefeng
 * Date: 2018/8/27
 * Time: 14:04
 */
namespace app\controllers\crontab;
use Yii;
use app\models\Elog;
use app\components\redis\RedisMarketingEmail;
use Ares333\Curl\Toolkit;

class AsynchronousController  extends \app\base\Controller
{
    private $asyn_proce = "asynchronous_processing";    //异步处理key
    /**
     * 异步处理
     * @author xianxuefeng
     * @date 2018-08-27
     */
    public function actionAsynchronousProcessing()
    {
        set_time_limit(0);
        //加一个 redis 缓存键，避免停止不下来
        $redis = new RedisMarketingEmail();
//        $info = $redis->del($this->asyn_proce);die;
        $info = $redis->hvals($this->asyn_proce);
        if (empty($info)) {
            return;
        }
        $mothod = strtolower(Yii::$app->request->getMethod());
        $threads = Yii::$app->request->$mothod('threads') ?  Yii::$app->request->$mothod('threads'): 20;
        //采用 curl 的多线程同时请求多个
        $toolkit = new Toolkit();
        $curl = $toolkit->getCurl();
        $curl->onInfo = array(
            $toolkit,
            'onInfo'
        );
        $i = 0;
        foreach ($info as $json) {
            if ($i >= $threads) {
                break;
            }
            $val = \GuzzleHttp\json_decode($json,true);
            if (empty($val['web_url'])) {
                //告警
                continue;
            }
            if (empty($val['retry_count'])) {   //重试次数
                $val['retry_count'] = 1;
            }else {
                ++$val['retry_count'];
            }
            $updatejson = \GuzzleHttp\json_encode($val);
            if ($val['retry_count'] > 3) {    //重复次数大于三次发警告
                Elog::logCrontab($updatejson, 'AsynchronousProcessing','exception'); // 记录信息到elog
            }
            $redis->hset($val['key'],$val['field'],$updatejson);
            $domain_name = yii::$app->request->hostInfo;
            $curl->add(
                array(
                    'opt' => array(
//                        CURLOPT_URL =>  $val['web_url']. '&i=' . $i."&XDEBUG_SESSION_START=PHPSTORM".'&json='.$json,
                        CURLOPT_URL =>  $domain_name . $val['web_url']. '&i=' . $i.'&json='.$json,
                      //  CURLOPT_COOKIE  => "staging=true;Domain=.appinthestore.com;Path=/",    //预发布cookie
                    ),
                )

            );
            ++$i;
        }
        $curl->start();

    }
}